﻿// Project VkAPI
// Created by CodeBorn, TV-42, NTUU "KPI" on 02.07.2016
// Updated on 02.07.2016

using System;
using System.Linq;
using System.Text;

namespace Vk.Methods.Common
{
    public static class NamingCaseExtensions
    {
        /// <summary>
        ///     Converts snake_case to camelCase
        /// </summary>
        /// <param name="snakeString">A string in snake_case</param>
        public static string ToCamelCase(this string snakeString)
        {
            return snakeString.Split('_').Aggregate((a, b) =>
            {
                var withFirstBigLetter = new StringBuilder(b)
                {
                    [0] = char.ToUpperInvariant(b[0])
                };

                return a + withFirstBigLetter.ToString();
            });
        }

        /// <summary>
        ///     Converts camelCase to snake_case
        /// </summary>
        /// <param name="camelString">A string in CamelCase</param>
        public static string ToSnakeCase(this string camelString)
        {
            var indicesOfBigLetters =
                camelString.Select((x, i) => new Tuple<char, int>(x, i))
                           .Where((c, i) => i != 0 && char.IsUpper(c.Item1))
                           .Select(c => c.Item2)
                           .ToArray();
            if (indicesOfBigLetters.Any())
            {
                var strBuilder = new StringBuilder(camelString);
                for (var i = 0; i < indicesOfBigLetters.Length; i++)
                {
                    var pos = indicesOfBigLetters[i] + i;

                    //Replace a big letter with the small one
                    strBuilder[pos] = char.ToLowerInvariant(strBuilder[pos]);

                    strBuilder.Insert(pos, '_');
                }
                return strBuilder.ToString();
            }
            return camelString.ToLower();
        }

        public static string WithFirstBigLetter(this string str)
        {
            return new StringBuilder(str)
            {
                [0] = char.ToUpperInvariant(str[0])
            }.ToString();
        }

        public static string WithFirstSmallLetter(this string str)
        {
            return WithSmallLetter(str, 0);
        }

        private static string WithSmallLetter(string str, int index)
        {
            return new StringBuilder(str)
            {
                [index] = char.ToLowerInvariant(str[index])
            }.ToString();
        }
    }
}